package com.diipo.weibo;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
  
import com.diipo.weibo.utils.HttpUtils;   

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory; 
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class CreateWeiBoActivity extends Activity implements OnClickListener{
	
	public static String UPLOAD_PIC_Temp=Environment.getExternalStorageDirectory()+"/upload_temp.jpg";
	private String TAG = CreateWeiBoActivity.class.getSimpleName();
	private SharedPreferences mPrefs;
	private Button mBack;
	private Button mSend;
	private Button mSearchContacts;
	private EditText mEditTextMsg;
	private String mStrMsg;
	private TextView mTitle;
	private String mCreateUrl = "/api/statuses/create.json?api_key=";  //发布微博消息
	private String mReplyeUrl = "/api/statuses/comments/create.json?api_key="; //回复微博消息
	private String mCreatePrivateUrl = "/api/direct_messages/create.json?api_key="; //发送微博私信
	private String mReplyPrivateUrl = "/api/direct_messages/reply.json?api_key="; //回复微博私信
	private Context mctx;
	private EditText mEditMsg;
	private ImageView image;
	private Button pic;
	private Button huati;
	private Button user;
	
//	private final int CREATE_WEIBO = 10;
//	private final int REPLY_WEIBO = 11;
//	private final int CREATE_PRIVATE = 12;
//	private final int REPLY_PRIVATE = 13;
	
	private String mIntentRet;
//	private String mDirectEmail = null;
	private String mDirectName = null;
	private String mId;
	private Intent mIntent;
	
	private String mPrivateUserid;
	private String mPrivateUserName = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// Hide title 
        requestWindowFeature( Window.FEATURE_NO_TITLE );
		setContentView(R.layout.create_view);
		
		mBack = (Button) findViewById(R.id.create_back);
		mSend = (Button) findViewById(R.id.send_btn);
		
		pic = (Button) findViewById(R.id.pic);
		huati = (Button) findViewById(R.id.huati);
		user = (Button) findViewById(R.id.user);
		pic.setOnClickListener(this);
		huati.setOnClickListener(this);
		user.setOnClickListener(this);
		
		registerForContextMenu(pic); 
		
		mSearchContacts = (Button) findViewById(R.id.find_contacts);
		mEditTextMsg = (EditText) findViewById(R.id.edittext_msg);
		mTitle = (TextView) findViewById(R.id.title_txt);
		mEditMsg = (EditText) findViewById(R.id.edittext_msg);
		 image = (ImageView) findViewById(R.id.iamge);
		mctx = this;
		
		mPrefs = getSharedPreferences(ConfigInfo.USER_PREFERENCES,MODE_PRIVATE);
		
		mIntent = getIntent();
		mIntentRet = mIntent.getStringExtra(ConfigInfo.COMM.SEND_TYPE);
		mPrivateUserName = mIntent.getStringExtra(ConfigInfo.COMM.SEND_LETTER);
		mPrivateUserid = mIntent.getStringExtra(ConfigInfo.COMM.USER_ID);
		mDirectName = mIntent.getStringExtra(ConfigInfo.COMM.DIRECT_MENTION);
		if(mDirectName != null){
			mEditMsg.setText("@" + mDirectName + " ");
		}
		if(mPrivateUserName != null){
			mSearchContacts.setVisibility(View.VISIBLE);
			mSearchContacts.setText(mctx.getString(R.string.search_contacts) + " : " + mPrivateUserName);
		}
		mId = mIntent.getStringExtra(ConfigInfo.COMM.MSG_ID);
		if(mIntentRet.equals(ConfigInfo.COMM.WEIBO_MSG)){
			mTitle.setText(mctx.getString(R.string.create_weibo_title));
		}else if(mIntentRet.equals(ConfigInfo.COMM.WEIBO_LETTER)){
			mSearchContacts.setVisibility(View.VISIBLE);
			mTitle.setText(mctx.getString(R.string.add_reply_title));
		}else if(mIntentRet.equals(ConfigInfo.COMM.WEIBO_MSG_REPLY)){
			mTitle.setText(mctx.getString(R.string.add_reply_title));
		}else if(mIntentRet.equals(ConfigInfo.COMM.WEIBO_LETTER_REPLY)){
			mTitle.setText(mctx.getString(R.string.add_reply_title));
		}else{
			
		}
		Log.e(TAG, " mIntentRet = " + mIntentRet); 
		
		mBack.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent();  
				Bundle b = new Bundle();  
				b.putString(ConfigInfo.COMM.SEND_TYPE, "0"); 
				i.putExtras(b);  
				setResult(ConfigInfo.CALLBACK_CREATE_WEIBO, i);  
				finish();
			}
		});
		
		
		mSend.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.e(TAG, " send msg or create weibo here......");
				mStrMsg = mEditTextMsg.getText().toString().trim();
				if (!mStrMsg.equals("") && mStrMsg != null){
					if(mIntentRet.equals(ConfigInfo.COMM.WEIBO_MSG)){ // 消息
						new AsyncDataLoader(asyncRemoteCallback,mctx,mCreateUrl,"","","").execute();
					}else if(mIntentRet.equals(ConfigInfo.COMM.WEIBO_MSG_REPLY)){//消息回复
						new AsyncDataLoader(asyncRemoteCallback,mctx,mReplyeUrl,"","","").execute();
					}else if(mIntentRet.equals(ConfigInfo.COMM.WEIBO_LETTER)){
						if(null == mPrivateUserName){
							Toast.makeText(mctx,mctx.getString(R.string.no_target_name), 3000).show();
							return;
						}
						new AsyncDataLoader(asyncRemoteCallback,mctx,mCreatePrivateUrl,"","","").execute();
					}else if(mIntentRet.equals(ConfigInfo.COMM.WEIBO_LETTER_REPLY)){
						new AsyncDataLoader(asyncRemoteCallback,mctx,mReplyPrivateUrl,"","","").execute();
					}else{
						//do what here? + by pyb
					}
				}else{
					Toast.makeText(mctx, mctx.getString(R.string.msg_error), 3000).show();
				}
			}
		});
		
		mSearchContacts.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(CreateWeiBoActivity.this,ContactsActivity.class);;
				i.putExtra(ConfigInfo.COMM.SEND_TYPE,ConfigInfo.COMM.WEIBO_LETTER);
				startActivityForResult(i,ConfigInfo.CALLBACK_CREATE_LETTER);
			}
		});
	}
	
	private static final int ITEM1 = Menu.FIRST;  
	  
    private static final int ITEM2 = Menu.FIRST + 1;   
	@Override  
    public void onCreateContextMenu(ContextMenu menu, View v,  
            ContextMenuInfo menuInfo) {  
  
        // 添加菜单项  
		menu.setHeaderTitle("选择上传方式：");
        menu.add(0, ITEM1, 0, "拍照上传");  
        menu.add(0, ITEM2, 0, "手机相册");    
          
            }  
  
    // 上下文菜单选中事项 通过选中不同的按钮来改变TextView的背景颜色  
    @Override  
    public boolean onContextItemSelected(MenuItem item) {  
  
        switch (item.getItemId()) {  
        case ITEM1: 
        	takePhoto();
            break;  
        case ITEM2:    
        	getLocalPicture();
            break;  
         
  
        }  
        return true;  
    }  
    public void takePhoto(){
    	try{
			   if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { 
        		Intent  i=new Intent("android.media.action.IMAGE_CAPTURE");
        		File tmpFile = new File(UPLOAD_PIC_Temp);  
        				// 获取这个图片的URI 
        		  originalUri = Uri.fromFile(tmpFile);//这是个实例变量，方便下面获取图片的时候用

        		i.putExtra(MediaStore.EXTRA_OUTPUT, originalUri);
        		startActivityForResult(i, 1);
        	}else{
        		new AlertDialog.Builder(CreateWeiBoActivity.this).setTitle("提示")
    			 .setMessage("请先确定正确加载SD卡？")
    			 .setPositiveButton("确定", new DialogInterface.OnClickListener() {
    				public void onClick(DialogInterface dialog, int whichButton) {
    					 
    				}
    			  }) 
    			  .show(); 
        	}
		   }catch(Exception e){}
		 
 }
 
 public void getLocalPicture(){ 
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		startActivityForResult(intent, 2);
	}
 
 
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1) { 
            if(resultCode == RESULT_OK){
            	//openImagetoCrap(2);
            	try{
            		File f = new File(UPLOAD_PIC_Temp);
    			    FileInputStream is = null;
    			    is = new FileInputStream(f); 
    			    Bitmap bm = BitmapFactory.decodeStream(is, null, null); 
    			    image.setVisibility(View.VISIBLE);
    			    image.setImageBitmap(bm);
            	}catch(Exception e){}
            } 
        }
		
		 if(requestCode==2){
				if (resultCode != RESULT_OK) {
					return;
				}
				try {
			   ContentResolver resolver = getContentResolver(); 
			   originalUri = data.getData();
			   InputStream is = null;  
			   is = resolver.openInputStream(originalUri); 
			   BitmapFactory.Options opts = new BitmapFactory.Options();
			   opts.inSampleSize=7;
			   Bitmap bm = BitmapFactory.decodeStream(is,null,opts);
			   //Utility.savePictures(bm,this); 
			   
//			    Drawable d = new BitmapDrawable(bm);
			     
				image.setVisibility(View.VISIBLE);
				 image.setImageBitmap(bm);
			    
			   
			    
			}catch (Exception e) {
			}
			 
			 
		}
		if(null == data){
			Log.e(TAG," data == null here,some exception happend here...");
			return;
		}
		Log.e(TAG, " onActivityResult() called  resultCode = " + resultCode + " requestCode = " + requestCode);
		Log.e(TAG, " onActivityResult() called  ret intent = " + data.getStringExtra(ConfigInfo.COMM.SEND_TYPE));
		String str = data.getStringExtra(ConfigInfo.COMM.SEND_TYPE);
		Log.e(TAG, " str = " + str);
		if(ConfigInfo.CALLBACK_CREATE_LETTER == requestCode){
			if(str.equals(ConfigInfo.COMM.WEIBO_LETTER)){
//				new AsyncDataLoader(asyncRemoteCallback,this,url_activity,"","","").execute();
				mPrivateUserName = data.getStringExtra(ConfigInfo.COMM.USER_NAME);
				mPrivateUserid = data.getStringExtra(ConfigInfo.COMM.USER_ID);
				Log.e(TAG, " onActivityResult() called  mPrivateUserName = "+mPrivateUserName + ", mPrivateUserid = "+ mPrivateUserid );
				mSearchContacts.setText(mctx.getString(R.string.search_contacts) + " : " + mPrivateUserName);
			}
		} 
		
	}
	
	/**
	 * 异步加载服务器上的微博数据的监听器,已查看和未查看 消息
	 */
	private AsyncDataLoader.Callback asyncRemoteCallback = new AsyncDataLoader.Callback() {
		
		List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
		String mRet = null;
//		list.add(new BasicNameValuePair("text", sb));

		@Override
		public void onStart(String address, String more) {
			// TODO Auto-generated method stub
			StringBuffer url = new StringBuffer();
			url.append(mPrefs.getString(ConfigInfo.PREF_SERVER_ADDRESS, mPrefs
					.getString(ConfigInfo.PREF_SERVER_ADDRESS,ConfigInfo.COMM.CONST_SERVER_ADDRESS)));
			url.append(address);
			url.append(ConfigInfo.COMM.APY_KEY);
			
			String username = mPrefs.getString(ConfigInfo.PREF_USERNAME, "");
			String passwd = mPrefs.getString(ConfigInfo.PREF_PASSWORD, "");
			if(mIntentRet.equals(ConfigInfo.COMM.WEIBO_MSG)){
				//发布消息
				list.add(new BasicNameValuePair("text", mStrMsg));
			}else if(mIntentRet.equals(ConfigInfo.COMM.WEIBO_MSG_REPLY)){
				String detail_id = mIntent.getStringExtra(ConfigInfo.COMM.DETAIL_ID);
				list.add(new BasicNameValuePair("id", detail_id));		
				list.add(new BasicNameValuePair("text", mStrMsg));
				Log.e(TAG, " onStart() called  send msg reply here................ ");
			}else if(mIntentRet.equals(ConfigInfo.COMM.WEIBO_LETTER)){
				
				list.add(new BasicNameValuePair("to_userid", mPrivateUserid));		
				list.add(new BasicNameValuePair("text", mStrMsg));
				Log.e(TAG, " onStart() called  send private letter here,mPrivateUserid = " + mPrivateUserid);
			}else if(mIntentRet.equals(ConfigInfo.COMM.WEIBO_LETTER_REPLY)){
				String detail_id = mIntent.getStringExtra(ConfigInfo.COMM.DETAIL_ID);
				list.add(new BasicNameValuePair("id", detail_id));		
				list.add(new BasicNameValuePair("text", mStrMsg));
				Log.e(TAG, " onStart() called  reply private letter here= ================   ");
			}else{
				
			}
			mRet = HttpUtils.doPost2(url.toString(), username,passwd, list);
			Log.e(TAG, " onStart() called,url = " + url.toString());
			Log.e(TAG, " onStart() called,mRet = " + mRet);
			
		}

		@Override
		public void onStart(String address, String arg1, String arg2) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onFinish() {
			// TODO Auto-generated method stub
			if (mRet != ConfigInfo.HTTPRETURN.COMMHTTPERRORS 
					&& mRet != ConfigInfo.HTTPRETURN.HTTP_ERROR_400 
					&& mRet != ConfigInfo.HTTPRETURN.HTTP_ERROR_401 
					&& mRet != ConfigInfo.HTTPRETURN.HTTPERROR ) {
				Intent i = new Intent();  
				Bundle b = new Bundle();  
				if(mIntentRet.equals(ConfigInfo.COMM.WEIBO_MSG)){ // 消息
					b.putString(ConfigInfo.COMM.SEND_TYPE, ConfigInfo.COMM.WEIBO_MSG); 
					i.putExtras(b);  
					setResult(ConfigInfo.CALLBACK_CREATE_WEIBO, i);  
					
				}else if(mIntentRet.equals(ConfigInfo.COMM.WEIBO_MSG_REPLY)){//消息回复
					b.putString(ConfigInfo.COMM.SEND_TYPE, ConfigInfo.COMM.WEIBO_MSG_REPLY); 
					b.putString(ConfigInfo.COMM.MSG_ID, mId);
					i.putExtras(b);
					setResult(ConfigInfo.CALLBACK_REPLY_WEIBO, i);  
				}else if(mIntentRet.equals(ConfigInfo.COMM.WEIBO_LETTER)){//发私信
					b.putString(ConfigInfo.COMM.SEND_TYPE, ConfigInfo.COMM.WEIBO_LETTER); 
					i.putExtras(b);  
					setResult(ConfigInfo.CALLBACK_CREATE_LETTER, i); 
					mPrivateUserName = null;
				}else if(mIntentRet.equals(ConfigInfo.COMM.WEIBO_LETTER_REPLY)){//私信回复
					b.putString(ConfigInfo.COMM.SEND_TYPE, ConfigInfo.COMM.WEIBO_LETTER_REPLY); 
					i.putExtras(b);  
					setResult(ConfigInfo.CALLBACK_REPLY_LETTER, i); 
				}else{
					//do what here? + by pyb
				}
				finish();  
				Toast.makeText(mctx,mctx.getString(R.string.send_ok), 3000).show();
			}else {
				Toast.makeText(mctx, mctx.getString(R.string.send_fail), 3000).show();
			}
		}
		
		@Override
		public void onPrepare() {
			// TODO Auto-generated method stub
			
		}
	};


	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		Log.e(TAG, " onStop()  called ..... "); 
	}
	
	// NullPointerException in the onActivityResult
	public boolean onKeyDown(int keyCode, KeyEvent event) {// 捕捉返回键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Log.e(TAG, " onKeyDown()  back called ..... "); 
			Intent i = new Intent();  
			Bundle b = new Bundle();  
			b.putString(ConfigInfo.COMM.SEND_TYPE, "-1"); 
			i.putExtras(b);  
			setResult(ConfigInfo.CALLBACK_CREATE_WEIBO, i);
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.e(TAG, " onDestroy() called ..... "); 
//		Intent i = new Intent();  
//		Bundle b = new Bundle();  
//		b.putString(ConfigInfo.COMM.SEND_TYPE, "0"); 
//		i.putExtras(b);  
//		setResult(CREATE_WEIBO, i);  
	}
	 Uri originalUri ;
	@Override
	public void onClick(View v) {
		switch(v.getId()){ 
		   case R.id.pic:
			   pic.performLongClick();
			   break;
		   case R.id.user:
			   try{
				   try{
					   String content=mEditTextMsg.getEditableText().toString().trim();
					   content+="@";
					   mEditTextMsg.setText(content);
				   }catch(Exception e){}
			   }catch(Exception e){}
			   break;
		   case R.id.huati:
			   try{
				   String content=mEditTextMsg.getEditableText().toString().trim();
				   content+="#插入新话题#";
				   mEditTextMsg.setText(content);
			   }catch(Exception e){}
			   break;
		
	    }
		
	}
		 
	 
}
